package com.syspeak.makereap.workflow.web.mvc.explorer;

import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.impl.persistence.entity.DeploymentEntity;
import org.activiti.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.support.BindingAwareModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.orm.PageRequest.Sort;
import org.springside.modules.orm.PropertyFilter;

import com.syspeak.makereap.workflow.modules.activiti.ActivitiRepositoryService;
import com.syspeak.makereap.workflow.web.mvc.BaseMvcController;
import com.syspeak.modules.spring.web.json.JsonExtPage;
import com.syspeak.modules.spring.web.servlet.mvc.annotation.JsonConfig;
import com.syspeak.modules.web.json.ExtPage;
import com.syspeak.modules.workflow.activiti.AbstractRepositoryService;

/**
 * Restful流程部署Controller
 * @company SysPeak (C) Copyright
 * @category DeploymentController
 * @version 1.0
 * @since 2011-10-13
 * @author JemiZhuu(周士淳)
 */
@Controller
@RequestMapping(value = "explorer/deployment")
public class DeploymentController extends BaseMvcController {
	private static final String BAR = ".bar";

	@RequestMapping(method = RequestMethod.GET)
	@JsonConfig(excludeProperties = ".*\\.resources", ignoreProperties = { "" })
	public String index(JsonExtPage<Deployment> page, HttpServletRequest request, Model model) {
		page = this.list(page, request);
		model.addAttribute(PAGE_BEAN, page);
		return getIndexViewName();
	}

	@RequestMapping(method = RequestMethod.GET, value = "list")
	@ResponseBody
	@JsonConfig(excludeProperties = ".*\\.resources", ignoreProperties = { "" })
	public <T extends ExtPage<Deployment>> T list(T page, HttpServletRequest request) {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		if (!page.isOrderBySetted()) {
			page.setOrderBy(AbstractRepositoryService.ID);
			page.setOrderDir(Sort.ASC);
		}
		page = repositoryService.findDeploymentPage(page, filters);
		page.setSuccess(true);
		return page;
	}

	@RequestMapping(method = RequestMethod.GET, value = "new")
	public String editNew() {
		return getInputViewName();
	}

	@RequestMapping(method = RequestMethod.GET, value = "{sid}/edit")
	public String edit(DeploymentEntity entity) {
		throw new HttpClientErrorException(HttpStatus.BAD_REQUEST);
	}

	@RequestMapping(method = RequestMethod.PUT, value = "{id}")
	public String update(DeploymentEntity entity) {
		throw new HttpClientErrorException(HttpStatus.BAD_REQUEST);
	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(MultipartFile deploymentResources, HttpServletRequest request) throws Exception {
		try {
			String fileName = deploymentResources.getOriginalFilename();
			InputStream inputStream = deploymentResources.getInputStream();
			if (fileName.toLowerCase().endsWith(BAR)) {
				inputStream = new ZipInputStream(inputStream);
			}
			Deployment deployment = repositoryService.createDeployment(inputStream,
					deploymentResources.getOriginalFilename());
			System.out.println(deployment);
		} catch (Exception e) {
			return editNew();
		}
		return index(new JsonExtPage<Deployment>(), request, new BindingAwareModelMap());
	}

	@RequestMapping(method = RequestMethod.GET, value = "{id}")
	public @ResponseBody
	String show(@PathVariable String id) {
		Deployment deployment = repositoryService.getDeployment(id);
		//return getInputViewName();
		return deployment + "真好了啊!";
	}

	@RequestMapping(method = RequestMethod.DELETE, value = "{id}")
	public String destroy(@PathVariable String id, HttpServletRequest request) {
		if (id != null) {
			deleteDeployment(id);
		}
		return index(new JsonExtPage<Deployment>(), request, new BindingAwareModelMap());
	}

	private void deleteDeployment(String deploymentId) {
		repositoryService.deleteDeployment(deploymentId);
	}

	private ActivitiRepositoryService repositoryService;

	@Autowired
	public void setRepositoryService(ActivitiRepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}
}